package com.example;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author lzj
 * @since 反射调用方法
 */
public class TestCall {

    public static class Inner {
        public int sum(int a, int b) {
            return a + b;
        }

        private int sum(int a, int b, int c) {
            return a + b + c;
        }

        public String sum(String a, String b) {
            return a + b;
        }

        public void hello() {
            System.out.println("hello world");
        }
    }
    
    public static void main(String s[]) {
        Inner inner = new Inner();
        Class clazz = inner.getClass();
        Method method = null;
        try {
            //根据方法名和参数列表得到某一方法
            method = clazz.getDeclaredMethod("sum", int.class, int.class, int.class);
            method.setAccessible(true);
            //没有返回值返回null
            Object obj = method.invoke(inner, 1, 2, 3);
            System.out.println(obj);
            //没有参数就不写
            method = clazz.getDeclaredMethod("hello");
            method.invoke(inner);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}







